package com.chuangke.common.utils;

import java.security.Principal;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * Security相关操作
 *
 * @author chuangke
 * @date Nov 20, 2018
 */
public class SecurityUtils {

    /**
     * 获取当前用户名
     *
     * @return
     */
    public static String getUserId() {
        Authentication authentication = getAuthentication();
        return getUserId(authentication);
    }

    /**
     * 获取用户名
     *
     * @return
     */
    public static String getUserId(Authentication authentication) {
        String username = null;
        if (authentication == null) {
            return null;
        }

        Object principal = authentication.getPrincipal();
        if (principal == null) {
            return null;
        }

        if (principal instanceof UserDetails) {
            username = ((UserDetails) principal).getUsername();
        } else if (principal instanceof Principal) {
            username = ((Principal) principal).getName();
        } else {
            username = principal.toString();
        }
        return username;
    }

    /**
     * 获取当前登录信息
     *
     * @return
     */
    public static Authentication getAuthentication() {
        if (SecurityContextHolder.getContext() == null) {
            return null;
        }
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
